package com.wanmait.gohome.controller.web;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.wanmait.gohome.pojo.*;
import com.wanmait.gohome.service.*;
import jdk.nashorn.internal.scripts.JO;
import net.sf.json.JSONArray;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestScope;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JsonConfig;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/web/information")
public class InfomationController {
    @Resource
    private InformationService informationService;
    @Resource
    private AreaService areaService;
    @Resource
    private LostTypeService lostTypeService;
    @Resource
    private UserinfoService userinfoService;
    @Resource
    private AutomatchService automatchService;
    @Resource
    private AttentionService attentionService;
    /**
     * @return 查询所有失踪类型
     */
    @GetMapping("chooseType")
    public ModelAndView lostType(HttpServletRequest request)
    {
        Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");
        ModelAndView mv = new ModelAndView();
        if(userinfo==null){
            request.getSession().setAttribute("goUrl",request.getRequestURI());
            mv.setViewName("/web/userinfo/login");
        }else{
            List<LostType> lostTypes = lostTypeService.findAll();
            mv.addObject("lostTypes", lostTypes);
        }
        return mv;
    }


    @RequestMapping("findPerson")//寻亲者发布寻人信息查询省市联动跳转到jsp
    public ModelAndView findCity() {
        List<Area> areas = areaService.findAll();
        HashMap<Integer, Area> typeMap = new HashMap<Integer, Area>();
        for (Area area : areas) {
            typeMap.put(area.getAreaId(), area);
        }
        List<Area> root = new ArrayList<>();//装省
        for (Area area : areas) {
            if (area.getParentId() == -1) {
                root.add(area);
            } else {
                Area parent = typeMap.get(area.getParentId());
                List<Area> areas1 = parent.getAreaList();
                if (areas1 == null) {
                    areas1 = new ArrayList<Area>();
                    parent.setAreaList(areas1);
                }
                areas1.add(area);
            }

        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("root", root);
        return mv;
    }


    @RequestMapping("findPersons")//寻亲者发布找人信息
    public ModelAndView findPerson(HttpServletRequest request, Information information, MultipartFile pic1) {
        String ext = FilenameUtils.getExtension(pic1.getOriginalFilename());
        String fileName = UUID.randomUUID() + "." + ext;
        String path = request.getServletContext().getRealPath("/web/uploadImages/") + fileName;
        File outFile = new File(path);
        try {
            pic1.transferTo(outFile);
        } catch (Exception e) {
        }
        information.setPic(fileName);
        informationService.insertPerson(information);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/web/information/success");
        return mv;
    }


    /**
     * @param request
     * @param information 个人中心  修改寻亲信息
     * @param pic1
     * @return
     */
    @PostMapping("updateByInformationId1")
    public String updateByInformationId1(HttpServletRequest request, Information information, MultipartFile pic1) {
        String ext = FilenameUtils.getExtension(pic1.getOriginalFilename());
        String fileName = UUID.randomUUID() + "." + ext;
        String path = request.getServletContext().getRealPath("/web/uploadImages/") + fileName;
        File outFile = new File(path);
        try {
            pic1.transferTo(outFile);
        } catch (Exception e) {
        }
        information.setPic(fileName);
        information.setEndEditTime(new Date());
        informationService.updateByInformationId(information);
        return "redirect:/web/index";
    }

    @RequestMapping("findFamily")//寻亲者发布寻亲信息查询省市联动跳转到jsp
    public ModelAndView findCities() {
        List<Area> areas = areaService.findAll();
        HashMap<Integer, Area> typeMap = new HashMap<Integer, Area>();
        for (Area area : areas) {
            typeMap.put(area.getAreaId(), area);
        }
        List<Area> root = new ArrayList<>();//装省
        for (Area area : areas) {
            if (area.getParentId() == -1) {
                root.add(area);
            } else {
                Area parent = typeMap.get(area.getParentId());
                List<Area> areas1 = parent.getAreaList();
                if (areas1 == null) {
                    areas1 = new ArrayList<Area>();
                    parent.setAreaList(areas1);
                }
                areas1.add(area);
            }

        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("root", root);
        return mv;
    }

    @PostMapping("findFamilys")//徐金鹏发布信息
    public ModelAndView findFamilys(HttpServletRequest request, Information information, MultipartFile picname, String lostTypeId) {
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        int id = Integer.parseInt(lostTypeId);
        String ext = FilenameUtils.getExtension(picname.getOriginalFilename());
        String fileName = UUID.randomUUID() + "." + ext;
        String path = request.getServletContext().getRealPath("/web/uploadImages/") + fileName;
        File outFile = new File(path);
        try {
            picname.transferTo(outFile);
        } catch (Exception e) {
        }
        information.setUserinfoId(userinfo.getId());
        information.setLostTypeId(id);
        information.setPic(fileName);
        informationService.insert(information);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/web/information/success");
        return mv;
    }


    @GetMapping("cities")//给省加事件ajax
    @ResponseBody
    public List<Area> cities(String areaId) {
        int id = Integer.parseInt(areaId);
        List<Area> area = areaService.findCities(id);
        return area;
    }

    /**
     * 跳转到志愿者发布信息页面
     */
    @GetMapping("findVolunteer")
    public ModelAndView findVolunteer() {
        List<Area> areas = areaService.volunteerFindAll();
        HashMap<Integer, Area> typeMap = new HashMap<Integer, Area>();
        for (Area area : areas) {
            typeMap.put(area.getAreaId(), area);
        }
        List<Area> root = new ArrayList<>();//装省
        for (Area area : areas) {
            if (area.getParentId() == -1) {
                root.add(area);
            } else {
                Area parent = typeMap.get(area.getParentId());
                List<Area> areas1 = parent.getAreaList();
                if (areas1 == null) {
                    areas1 = new ArrayList<Area>();
                    parent.setAreaList(areas1);
                }
                areas1.add(area);
            }

        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("root", root);
        return mv;
    }

    /**
     * 志愿者提交信息
     */
    @PostMapping("findVolunteer")
    public ModelAndView findVolunteer(Information information, HttpServletRequest request, MultipartFile photo) {
        String ext = FilenameUtils.getExtension(photo.getOriginalFilename());
        String fileName = UUID.randomUUID() + "." + ext;
        String path = request.getServletContext().getRealPath("/web/uploadImages/") + fileName;
        information.setPic(fileName);
        File outFile = new File(path);
        try {
            photo.transferTo(outFile);
        } catch (Exception e) {
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        int year = Integer.parseInt(sdf.format(new Date()));
        int ageStart = year - Integer.parseInt(information.getAgeStart());
        int ageEnd = year - Integer.parseInt(information.getAgeEnd());
        information.setAgeStart(ageStart + "");
        information.setAgeEnd(ageEnd + "");
        ModelAndView mv = new ModelAndView();
        informationService.insertByVolunteer(information);
        mv.setViewName("/web/information/success");
        return mv;
    }


    /**
     * 发布成功页面
     */
    @GetMapping("success")
    public void success() {
    }



    @RequestMapping("informationList")
    public ModelAndView informationList(Information information, String title) {//信息展示界面
        Integer lostTypeId = information.getLostTypeId();
        ModelAndView mv = new ModelAndView();
        if (lostTypeId == 0) {
            List<LostType> lostTypes = lostTypeService.findAll();
            PageInfo pageInfo = informationService.selectList1(information);
            mv.addObject("lostTypes", lostTypes);
            mv.addObject("pageInfo", pageInfo);
            mv.addObject("lostTypeId", lostTypeId);
        } else if (lostTypeId == 1 || lostTypeId == 2 || lostTypeId == 3) {
            List<LostType> lostTypes = lostTypeService.findAll();
            PageInfo pageInfo = informationService.selectList(information);
            mv.addObject("lostTypes", lostTypes);
            mv.addObject("pageInfo", pageInfo);
            mv.addObject("lostTypeId", lostTypeId);
        }
        return mv;
    }

    @RequestMapping("showList")//详细信息展示界面
    @ResponseBody
    public ModelAndView showList(Integer id,HttpServletRequest request)
    {
        Userinfo userinfo = (Userinfo)request.getSession().getAttribute("userinfo");
        ModelAndView mv = new ModelAndView();
        if(userinfo!=null)
        {
            Attention attention = attentionService.findByUserIdAndInformationId(userinfo.getId(),id);
            if(attention!=null){
                mv.addObject("attention","true");
            }else{
                mv.addObject("attention","false");
            }
        }else{
            mv.addObject("attention","false");
        }
        informationService.pageviews(id);
        List<Information> information = informationService.findAllList();
        Information information1 = informationService.findByInformation(id);
        mv.addObject("information1", information1);
        mv.addObject("information", information);
        return mv;
    }


    @RequestMapping("souSuoInformation")//条件搜索solr
    @ResponseBody
    public ModelAndView souSuoInformation(String title) {
        System.out.println("wangxiuquan" + title);
        PageInfo<Information> pageInfo = informationService.findByTitle(title);
        List<LostType> lostTypes = lostTypeService.findAll();
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        mv.addObject("lostTypes", lostTypes);
        return mv;
    }



    /**
     *
     * @param informationId  查找相似
     */
    @GetMapping("likeList")
    @ResponseBody
    public ModelAndView autoMatch(Integer informationId)
    {
        ModelAndView mv = new ModelAndView();
        List<Automatch> automatches = automatchService.findByInformationId(informationId);
        List<Information> informations = new ArrayList<>();
        for(int i=0;automatches!=null&&i<automatches.size();i++)
        {
            Information information = informationService.findByInformation(automatches.get(i).getId());
            informations.add(information);
        }
        informations.forEach(information -> System.out.println(information));
        mv.addObject("informations",informations);
        return mv;
    }
   /* @RequestMapping("showList")//详细信息展示界面
    public ModelAndView showList1(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        Userinfo userinfos= userinfoService.findById(userinfo.getId());
        mv.addObject("userinfos",userinfos);
        return mv;
    }*/
}




